package com.miaosha.ms_02.service;

import com.miaosha.ms_02.domain.User;
import com.miaosha.ms_02.exception.GlobalException;
import com.miaosha.ms_02.prefix.MiaoshaUserKey;
import com.miaosha.ms_02.redis.JedisService;
import com.miaosha.ms_02.result.CodeMsg;
import com.miaosha.ms_02.util.MD5Util;
import com.miaosha.ms_02.vo.LoginVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description //TODO
 * @Author Administrator
 * @DATE 2020/9/18 20:32
 **/
@Service
public class MiaoshaUserService {

    @Autowired
    private UserService userService;

    @Autowired
    private JedisService jedisService;

    public  static final String COOKIE_NAME_TOKEN = "TOKEN";

    public Boolean login(LoginVo loginVo, String token){
        String mobile = loginVo.getMobile();
        String formPass = loginVo.getPassword();
        User user = userService.getUserById(mobile);
        if(user == null ){
            throw new GlobalException(CodeMsg.SESSION_ERROR);
        }
        String salt = user.getSalt();
        String dbPass = MD5Util.formToDB(formPass, salt);
        if(!dbPass.equals(user.getPassword())){
            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
        }
        //验证成功，加入缓存
        jedisService.set(MiaoshaUserKey.USERKEY_TOKEN_NAME,token,user,User.class);
        return true;
    }

    /**
     * @Description 根据 redisKey 从 redis 中获取数据
     * @param key redisKey
     * @return com.miaosha.ms_02.domain.User
     **/
    public User getUserByRedisKey(String key){
        if(StringUtils.isEmpty(key)){
            return  null;
        }
        User user = jedisService.get(MiaoshaUserKey.USERKEY_TOKEN_NAME, key, User.class);
        if(user == null){
            throw new GlobalException(CodeMsg.SESSION_ERROR);
        }
        return user;
    }
}
